<template>
  <div>
    <el-card shadow="hover" style="margin-bottom: 20px">
      <div class="flex-warp">
        <div class="flex-warp-item">
          <div class="flex-warp-item-box">
            <el-input placeholder="请输入题目名称"
                      size="small"
                      suffix-icon="el-icon-search"
                      v-model="listQueryParam.questionName"
            >
            </el-input>
          </div>
        </div>
        <div class="flex-warp-item">
          <div class="flex-warp-item-box">
            <el-input placeholder="请输入考试名称"
                      size="small"
                      suffix-icon="el-icon-search"
                      v-model="listQueryParam.examName"
            >
            </el-input>
          </div>
        </div>
        <div class="flex-warp-item">
          <div class="flex-warp-item-box">
            <el-button size="small"
                       icon="el-icon-search"
                       @click="search"
            >搜索
            </el-button>
          </div>
        </div>

        <div class="flex-warp-item">
          <div class="flex-warp-item-box">
            <el-button type="primary"
                       size="small"
                       icon="el-icon-refresh-right"
                       @click="refresh"
            >刷新
            </el-button>
          </div>
        </div>

        <div class="flex-warp-item">
          <div class="flex-warp-item-box">
            <el-button type="success"
                       size="small"
                       icon="el-icon-plus"
                       @click="add"
            >添加试题
            </el-button>
          </div>
        </div>

        <div class="flex-warp-item">
          <div class="flex-warp-item-box">
            <el-button type="danger"
                       size="small"
                       icon="el-icon-folder-delete"
                       @click="batchDel"
            >删除
            </el-button>
          </div>
        </div>
      </div>
    </el-card>
    <el-card shadow="hover"
             class="mt15"
    >
      <el-table :data="tableData"
                stripe
                ref="multipleTable"
                @selection-change="handleSelectionChange"
                style="width: 100%"
      >
        <el-table-column type="selection"
                         width="55"
        >
        </el-table-column>
        <el-table-column prop="id"
                         align="center"
                         label="题目编号"
        >
        </el-table-column>
        <el-table-column prop="questionName"
                         align="center"
                         label="题目名称"
        >
        </el-table-column>
        <!-- <el-table-column prop="answer"
                         align="center"
                         label="答案"
        >
        </el-table-column> -->
        <el-table-column align="center" label="答案">
          <template slot-scope="scope">
            <div v-if="scope.row.types === 0">
              <!-- 单选题 -->
              <span>{{ scope.row.answer }}</span>
            </div>
            <div v-else-if="scope.row.types === 1">
              <!-- 多选题 -->
              <span>{{ scope.row.answer }}</span>
            </div>
            <div v-else-if="scope.row.types === 2">
              <!-- 判断题 -->
              <span>{{ scope.row.answer === '√' ? '√' : '×' }}</span>
            </div>
            <div v-else>
              <!-- 填空题、主观题、其他 -->
              <span>{{ scope.row.answer }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="grade"
                         align="center"
                         label="分数"
        >
        </el-table-column>
        <el-table-column prop="types"
                         align="center"
                         label="分类"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.types == '0'">单选</span>
            <span v-if="scope.row.types == '1'">多选</span>
            <span v-if="scope.row.types == '2'">判断</span>
            <span v-if="scope.row.types == '3'">填空</span>
            <span v-if="scope.row.types == '4'">主观题</span>
            <span v-if="scope.row.types == '5'">其他</span>
          </template>
        </el-table-column>

        <el-table-column prop="examName"
                         align="center"
                         label="所属考试"
        >
        </el-table-column>
        <el-table-column prop="createTime"
                         align="center"
                         label="创建时间"
        >
        </el-table-column>
        <el-table-column fixed="right"
                         align="center"
                         label="操作"
        >
          <template slot-scope="scope">
            <el-button @click="updateClick(scope.row)"
                       type="text"
                       size="small"
            >编辑
            </el-button>
            <el-button type="text"
                       size="small"
                       @click="delClick(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="listQueryParam.current"
                  :limit.sync="listQueryParam.pageSize"
                  @pagination="getTableDataList"
      />
    </el-card>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="dialogTitle"
               :visible.sync="addOrUpdateDialogVisible"
               width="40%"
               :before-close="handleClose"
    >
      <el-form :model="formData"
               :rules="rules"
               ref="formData"
               label-width="100px"
      >
        <el-form-item label="题目名称"
                      prop="questionName"
        >
          <el-input v-model="formData.questionName"></el-input>
        </el-form-item>
        <!-- <el-form-item label="答案"
                      prop="answer"
        >
          <el-input v-model="formData.answer"></el-input>
        </el-form-item> -->
        <el-form-item label="分数"
                      prop="grade"
        >
          <el-input-number v-model="formData.grade" :precision="2" :step="0.1" :max="1000000"></el-input-number>
        </el-form-item>
        <el-form-item label="分类"
                      prop="types"
        >
          <el-radio-group v-model="formData.types">
            <el-radio :label="0">单选</el-radio>
            <el-radio :label="1">多选</el-radio>
            <el-radio :label="2">判断</el-radio>
            <el-radio :label="3">填空</el-radio>
            <el-radio :label="4">主观题</el-radio>
            <el-radio :label="5">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="答案" prop="answer">
          <div v-if="formData.types === 0">
            <!-- 单选题 -->
            <el-radio-group v-model="formData.answer">
              <el-radio label="A">A</el-radio>
              <el-radio label="B">B</el-radio>
              <el-radio label="C">C</el-radio>
              <el-radio label="D">D</el-radio>
            </el-radio-group>
          </div>
          <div v-else-if="formData.types === 1">
            <!-- 多选题 -->
            <el-checkbox-group v-model="formData.answerArray" @change="updateAnswerString">
              <el-checkbox label="A">A</el-checkbox>
              <el-checkbox label="B">B</el-checkbox>
              <el-checkbox label="C">C</el-checkbox>
              <el-checkbox label="D">D</el-checkbox>
            </el-checkbox-group>
          </div>
          <div v-else-if="formData.types === 2">
            <!-- 判断题 -->
            <el-radio-group v-model="formData.answer">
              <el-radio label="√">√</el-radio>
              <el-radio label="×">×</el-radio>
            </el-radio-group>
          </div>
          <div v-else>
            <!-- 填空题、主观题、其他 -->
            <el-input v-model="formData.answer" placeholder="请输入答案"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="所属考试"
                      prop="examId"
        >
          <el-select v-model="formData.examId" clearable placeholder="请选择所属考试">
            <el-option
              v-for="item in examIdOptions"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer"
      >
        <el-button @click="addOrUpdateDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitForm('formData')"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getList, insert, update, get, del, getExamDate } from '@/api/Questions/index'
import Pagination from '@/components/Pagination'
import { tableUtil } from '@/mixins/table'
import { Message } from 'element-ui'

export default {
  mixins: [tableUtil],
  components: {
    Pagination
  },
  data() {
    return {
      type: localStorage.getItem('examType'),
      listQueryParam: {
        current: 1,
        pageSize: 5
      },
      formData: {
        answer: '', // 默认为空字符串
        answerArray: [], // 多选题的答案数组
        types: null // 默认未选择分类
      },
      rules: {
        questionName: [
          { required: true, message: '请输入题目名称', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答案', trigger: 'blur' },
          { validator: this.validateAnswer, trigger: 'blur' }
        ],
        grade: [
          { required: true, message: '请输入分数', trigger: 'blur' }
        ],
        types: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        examId: [
          { required: true, message: '请选择所属考试', trigger: 'change' }
        ]
      },
      examIdOptions: []
    }
  },
  mounted() {
    this.getTableDataList()
    this.getExamDateList()
  },
  methods: {
    getTableDataList() {
      if (this.type == 1) {
        this.listQueryParam.teacherId = localStorage.getItem('examId')
      }
      getList(this.listQueryParam).then((res) => {
        this.total = res.data.total
        this.tableData = res.data.records
      })
    },
    updateClick(row) {
      this.dialogTitle = '修改'
      get(row.id).then((res) => {
        const data = res.data;
        if (data.types === 1) {
          // 多选题：将字符串转换为数组
          data.answerArray = data.answer.split('');
        } else {
          // 其他类型：确保 answerArray 是空数组
          data.answerArray = [];
        }
        this.formData = { ...data }; // 确保 formData 是一个新的对象
        // this.formData = res.data
        this.addOrUpdateDialogVisible = true
      })
    },
    delByIds(ids) {
      del(ids).then((res) => {
        Message.success('删除成功')
        this.getTableDataList()
      })
    },
    saveData() {
      // 多选题：将答案数组转换为字符串
      if (this.formData.types === 1) {
        this.formData.answer = this.formData.answerArray.join('');
      }

      // 其他类型：确保答案是字符串
      if (this.formData.types !== 1) {
        this.formData.answer = typeof this.formData.answer === 'string' ? this.formData.answer : '';
      }
      if (this.formData.id) {
        update(this.formData).then((res) => {
          Message.success('修改成功')
          this.addOrUpdateDialogVisible = false
          this.getTableDataList()
        })
      } else {
        insert(this.formData).then((res) => {
          Message.success('添加成功')
          this.addOrUpdateDialogVisible = false
          this.getTableDataList()
        })
      }
    },
    updateAnswerString() {
          // 将多选题答案数组转换为字符串
          this.formData.answer = this.formData.answerArray.join('');
        },
        validateAnswer(rule, value, callback) {
      if (this.formData.types === 1) { // 多选题
        if (this.formData.answerArray.length === 0) {
          callback(new Error('请选择答案'));
        } else {
          callback();
        }
      } else {
        if (!value) {
          callback(new Error('请输入答案'));
        } else {
          callback();
        }
      }
    },
    resetFormData() {
      this.formData = {
        answer: '',
        answerArray: [],
        types: null
      }
    },
    add() {
      this.dialogTitle = '添加试题'
      this.resetFormData() // 重置 formData
      this.addOrUpdateDialogVisible = true
    },
    getExamDateList() {
      getExamDate().then(res => {
        this.examIdOptions = res.data
      })
    }
  }
}
</script>
